#!/bin/bash
set -e

SCRIPT_HOME="$( cd "$( dirname "$0" )" && pwd )"

INDY_CLI_EXE=$(type -p indy-cli)

# =================================================================================================================
# Usage:
# -----------------------------------------------------------------------------------------------------------------
usage () {
  cat <<-EOF

  Thin wrapper around cli operations.

  Usage: $0 [command] [options]

  Commands:

  start-client
    - Default command if no other command is specified.

  reset
    - Delete all wallets and pools from the client container.

  init-pool <name/> <genesisUrl/>
    - Downloads the genesis file for a pool and sets it up with the specified name.
    - Allows the indy-cli to be connected to an arbitrary ledger.

  [command] [options]
    - Any command and options that can be executed by the container's shell.

  help
    - Print this usage documantation.

EOF
exit 1
}
# -----------------------------------------------------------------------------------------------------------------
# Functions:
# -----------------------------------------------------------------------------------------------------------------
function toLower() {
  echo $(echo ${@} | tr '[:upper:]' '[:lower:]')
}

function reset () {
  echo "Resetting pools ..."
  rm -rf ~/.indy_client/pool/*
  echo "Resetting wallets ..."
  rm -rf ~/.indy_client/wallet/*
  if [ -d ~/.indy_client/wallets ]; then
    rm -rf ~/.indy_client/wallets
  fi
}

function init-pool () {
  name=${1}
  genesisUrl=${2}
  if [ -z "${name}" ] || [ -z "${genesisUrl}" ]; then
    echo "init-pool:"
    echo "Expected; init-pool <name/> <genesisUrl/>."
    exit 1
  fi

  mkdir -p .indy_client/pool/${name}
  curl ${genesisUrl} -o .indy_client/pool/${name}/${name}.txn
}

function start-client () {
  ./scripts/start_client.sh "${@}"
}

function indy-cli() {
  
  for arg in "$@"; do
    # Remove recognized arguments from the list after processing.
    shift
    case "${arg}" in
      *=*)
        batchFileArgs+=" ${arg}"
        ;;
      *)
        # Detemine whether or not the arg is a recognized cli-script template.
        batchTemplate=$(find ./cli-scripts -type f -name "${arg}" 2>/dev/null)
        if [ -z "${batchTemplate}" ]; then
          # If not recognized, save it for later procesing ...
          set -- "$@" "${arg}"
        fi
        ;;
    esac
  done

  # ========================================================================
  # Prepare the cli batch script when using a template.
  # ------------------------------------------------------------------------
  if [ ! -z "${batchTemplate}" ]; then
    batchfile="${batchTemplate}.run"

    # ========================================================================
    # Set default storageType if storgae configuration has not been specified.
    # ------------------------------------------------------------------------
    if [[ "${batchFileArgs}" != *"storageType"* ]]; then
      batchFileArgs+=" storageType=default"
    fi

    if [[ "${batchFileArgs}" != *"storageConfig"* ]]; then
      batchFileArgs+=" storageConfig={}"
    fi

    if [[ "${batchFileArgs}" != *"storageCredentials"* ]]; then
      batchFileArgs+=" storageCredentials={}"
    fi
    # ========================================================================

    # ========================================================================
    # Set default outputFile name if not specified.
    # - Only for scripts that require an input file.
    # ------------------------------------------------------------------------
    if [[ "${batchFileArgs}" == *"inputFile"* ]] && [[ "${batchFileArgs}" != *"outputFile"* ]]; then
      cmd="${batchFileArgs} eval echo '\${inputFile}' | envsubst"
      inputPath=$(eval ${cmd})
      outputPath="${inputPath%/*}/signed-${inputPath##*/}"
      batchFileArgs+=" outputFile=${outputPath}"
    fi
    # ========================================================================

    escapedArgs=$(echo ${batchFileArgs} | sed "s~'~\\\'~g" | sed 's~\"~\\"~g')
    cmd="${escapedArgs} envsubst < ${batchTemplate} > ${batchfile}"
    eval ${cmd}
    indyCliArgs="${batchfile}"
  fi
  # ========================================================================

  eval ${INDY_CLI_EXE} ${@} ${indyCliArgs}
  
  # Clean up ...
  if [ -f "${batchfile}" ]; then
    rm -rf "${batchfile}"
  fi
}
# =================================================================================================================

COMMAND=${1}
if [ -z "${COMMAND}" ]; then
  COMMAND="start-client"
fi

case "${COMMAND}" in
  help)
    usage
    ;;
  *)
    escapedCmd=$(echo "${@}" | sed "s~'~\\\'~g" | sed 's~\"~\\"~g' | sed 's~,~\\,~g')
    eval ${escapedCmd}
    ;;
esac